// \u4e00-\u9fa5] 中文验证规则
import validate from 'wechat-validate'
Page({
  // 通过 behaviors 注入 validate 方法
  behaviors: [validate],
  data: {
    id: '',
    point: '',
    building: '',
    room: '',
    name: '',
    gender: '1',
    mobile: '',
    // 人像面照片
    idcardFrontUrl: '',
    // 国徽面照片
    idcardBackUrl: '',
  },
  // 校验规则
  rules: {
    name: [
      {
        required: true,
        message: '请填写业主姓名!',
      },
      {
        pattern: /^[\u4e00-\u9fa5]{2,5}$/,
        message: '姓名为2～5个中文',
      },
    ],
    mobile: [
      {
        required: true,
        message: '当前手机号不能为空!',
      },
      {
        // pattern: /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/,
        pattern: /^((\d3)|(\d{3}\-))?13[0-9]\d{8}|15[89]\d{8}/,
        message: '请检查手机号码是否正确!',
      },
    ],
    idcardFrontUrl: [
      {
        required: true,
        message: '身份证人像面未上传!',
      },
    ],
    idcardBackUrl: [
      {
        required: true,
        message: '身份证国徽面未上传!',
      },
    ],
  },

  // 填写业主姓名
  setName(e) {
    this.setData({
      name: e.detail,
    })
  },

  // 选择性别
  setGender(e) {
    this.setData({
      gender: e.detail,
    })
  },

  // 输入手机号
  setMobile(e) {
    this.setData({
      mobile: e.detail,
    })
  },

  // 上传人像面身份证
  updateIdcardBackUrl() {
    const _this = this
    wx.chooseMedia({
      count: 9,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        wx.uploadFile({
          url: 'https://live-api.itheima.net/upload',
          //小程序本地的路径
          filePath: res.tempFiles[0].tempFilePath,
          //后台获取我们图片的key
          name: 'file',
          header: {
            Authorization: `Bearer ${getApp().getToken()}`,
          },
          success({ data }) {
            _this.setData({
              idcardFrontUrl: JSON.parse(data).data.url,
            })
            wx.utils.toast('上传成功')
          },
        })
      },
    })
  },

  // 上传国徽面身份证
  updateIdcardFrontUrl() {
    const _this = this
    wx.chooseMedia({
      count: 9,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        wx.uploadFile({
          url: 'https://live-api.itheima.net/upload',
          //小程序本地的路径
          filePath: res.tempFiles[0].tempFilePath,
          //后台获取我们图片的key
          name: 'file',
          header: {
            Authorization: `Bearer ${getApp().getToken()}`,
          },
          success({ data }) {
            _this.setData({
              idcardBackUrl: JSON.parse(data).data.url,
            })
            return wx.utils.toast('上传成功')
          },
        })
      },
    })
  },

  async goList() {
    // 验证 rules 中定义的全部数据
    const isAllValid = this.validate()
    if (!isAllValid) return
    const data = {
      point: this.data.point,
      building: this.data.building,
      room: this.data.room,
      name: this.data.name,
      gender: this.data.gender - 0,
      mobile: this.data.mobile,
      FrontUrl: this.data.FrontUrl,
      idcardFrontUrl: this.data.idcardFrontUrl,
      idcardBackUrl: this.data.idcardBackUrl,
    }

    const id = this.data.id
    if (id) {
      const editData = {
        id,
        ...data,
      }
      await wx.http.post('/room', editData)
      wx.utils.toast('编辑成功')
    } else {
      await wx.http.post('/room', data)
      wx.utils.toast('添加成功')
    }

    return wx.reLaunch({
      url: '/house_pkg/pages/list/index',
    })
  },

  removePicture(ev) {
    // 移除图片的类型（身份证正面或反面）
    const type = ev.mark?.type
    this.setData({
      [type]: '',
    })
  },

  async onLoad({ id, point, building, room }) {
    if (id) {
      wx.setNavigationBarTitle({
        title: '编辑房屋信息',
      })
      this.setData({
        id,
      })
      const { data } = await wx.http.get(`/room/${id}`)
      return await this.setData({
        point: data.point,
        building: data.building,
        room: data.room,
        name: data.name,
        gender: data.gender + '',
        mobile: data.mobile,
        idcardFrontUrl: data.idcardFrontUrl,
        idcardBackUrl: data.idcardBackUrl,
        status: data.status,
      })
    } else {
      this.setData({
        id,
        point,
        building,
        room,
      })
    }
  },
})
